<script setup>
import {onMounted, ref} from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useTokenStore} from "@/stores/token.js";
import { userRegisterAService, userRegisterBService, userLoginService } from '@/api/user'
import {sendSmsCodeApi} from "@/api/message.js";
import useUserInfoStore from "@/stores/userInfo.js";
import {useBlackSotre} from '@/stores/black'
import {useDark, useToggle} from "@vueuse/core";
import emitter from "@/utils/buts.js";
import {sendECode} from "@/api/email.js";
const isDark = useDark();
const isBlack = useBlackSotre()
const router = useRouter()
const tokenStore = useTokenStore()
const userInfo = useUserInfoStore()
// 登录类型（username/phone）
const loginType = ref('username')
const isRegister = ref(false)
// 登录表单数据
const loginData = ref({
  username: '',
  password: '',
  phone: '',
  authCode: ''
})
function handleDark() {
  useToggle(isDark)
}

onMounted(()=>{
  emitter.on("login", () => {
    handleDark();
  });
})
// 验证码发送状态
const isSmsCodeSending = ref(false)
const isSmsCodeSending2 = ref(false)
const smsCodeBtnText = ref('获取验证码')
const smsCodeBtnText2 = ref('获取验证码')

// 切换登录类型
const toggleLoginType = () => {
  loginType.value = loginType.value === 'username' ? 'phone' : 'username'
}
// 发送短信验证码
const sendSmsCode = async (phone) => {
  if (phone==='') {
    ElMessage.warning('请输入手机号')
    return
  }
  const phoneReg = /^1[3-9]\d{9}$/
  if (!phoneReg.test(phone.trim())) {
    ElMessage.error('手机号格式不正确')
    return false
  }
  try {
    isSmsCodeSending.value = true
    await sendSmsCodeApi(phone)
    ElMessage.success('验证码已发送')
    startSmsCodeCountdown()
  } catch (error) {
    ElMessage.error( '验证码发送失败')
  } finally {
    isSmsCodeSending.value = false
  }
}
// 发送邮箱验证码
const sendEmailCode = async (email) => {
  if (email==='') {
    ElMessage.warning('请输入邮箱')
    return
  }
  const emailReg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/
  if (!emailReg.test(email.trim())) {
    ElMessage.error('邮箱格式不正确')
    return false
  }
  try {
    isSmsCodeSending2.value = true
    await sendECode(email)
    ElMessage.success('验证码已发送')
    startSmsCodeCountdown2()
  } catch (error) {
    ElMessage.error( '验证码发送失败')
  } finally {
    isSmsCodeSending2.value = false
  }
}
// 手机验证码倒计时
const startSmsCodeCountdown = () => {
  let count = 60
  const timer = setInterval(() => {
    if (count <= 0) {
      clearInterval(timer)
      smsCodeBtnText.value = '获取验证码'
    } else {
      smsCodeBtnText.value = `${count}秒后重试`
      count--
    }
  }, 1000)
}
// 邮箱验证码倒计时
const startSmsCodeCountdown2 = () => {
  let count = 60
  const timer = setInterval(() => {
    if (count <= 0) {
      clearInterval(timer)
      smsCodeBtnText2.value = '获取验证码'
    } else {
      smsCodeBtnText2.value = `${count}秒后重试`
      count--
    }
  }, 1000)
}

// 登录逻辑
const handleLogin = async () => {
  try {
    let res
    if ((loginData.value.phone && loginData.value.authCode==='') || (loginData.value.username && loginData.value.password==='')) {
      ElMessage.error("信息不全")
      return
    }
    if (loginType.value === 'username') {
      res = await userLoginService({
        username: loginData.value.username,
        password: loginData.value.password,
      })
    } else {
      res = await userLoginService({
        username: null,
        password: null,
        phone: loginData.value.phone,
        auth_code: loginData.value.authCode
      })
    }
    userInfo.setInfo(res)
    if (res.message!== null) {
      console.log(res)
      tokenStore.setToken(res.token)
      ElMessage.success(res.message)
      await router.push('/layout')
    }
  } catch (error) {

    ElMessage.error(error.response?.data?.msg || '登录失败')
  }
}

// 注册表单数据
const registerData = ref({
  userType: 'enterprise_admin',
  username: '',
  realName:'',
  password: '',
  rePassword:'',
  phone: '',
  authCode_m: '',
  email: '',
  authCode_e: '',
  enterpriseId: '',
  enName: '',
})
const isValid = () => {
  const data = registerData.value;

  // 检查除 enterpriseId 和 enName 外的其他字段是否都不为空
  const otherFieldsValid = Object.entries(data).every(([key, value]) => {
    if (key === 'enterpriseId' || key === 'enName') return true; // 跳过这两个字段
    return value.trim() !== ''; // 使用 trim() 避免空格绕过检查
  });

  // 检查 enterpriseId 和 enName 不同时为空
  const enterpriseFieldsValid =
      data.enterpriseId.trim() !== '' || data.enName.trim() !== '';

  return otherFieldsValid && enterpriseFieldsValid;
};
// 注册逻辑
const handleRegister = async () => {
  let res
    if (!isValid()) {
      ElMessage.error("信息不全")
      return
  }
  if (registerData.value.enterpriseId === '' && registerData.value.rePassword==='') {
    ElMessage.error("企业信息未填写")
    return
  }
  if (registerData.value.password !== registerData.value.rePassword) {
    ElMessage.error("两次密码不一致")
    return
  }
  try {
    let dto = {
        username: registerData.value.username,
        password: registerData.value.password,
        realName: registerData.value.realName,
        phone: registerData.value.phone,
        authCode_m: registerData.value.authCode_m,
        authCode_e: registerData.value.authCode_e,
        email: registerData.value.email,
        enName: registerData.value.enName,
        enterpriseId: registerData.value.enterpriseId,
    }
    if (registerData.value.userType === 'enterprise_admin'){
      res = await userRegisterAService(dto)
    }else {
      res = await userRegisterBService(dto)
    }
      if (registerData.value.userType === 'normal_user'){
        ElMessage.info("请等候企业管理员审核")
        await router.push('/')
      }
      ElMessage.success('注册成功')
      tokenStore.setToken(res.token)
      userInfo.setInfo(res.data)
      await router.push('/layout')
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '注册失败')
  }
}
</script>

<template>

  <el-row class="login-page" :class="{ 'dark-mode': true }">
    <el-col :span="12" class="bg"><h1 id="title">在线审批系统</h1></el-col>

    <el-col :span="6" :offset="3" class="form">
      <!-- 注册表单 -->
      <el-form ref="registerForm" :model="registerData" v-if="isRegister" :rules="registerRules">
        <h1 style="font-family: 华文楷体,serif;color:darkslategray">用户注册</h1>
        <!-- 用户类型选择 -->
        <el-form-item label="用户类型" prop="userType">
          <el-radio-group v-model="registerData.userType">
            <el-radio label="enterprise_admin" value="enterprise_admin">企业管理员</el-radio>
            <el-radio label="normal_user" value="normal_user">普通用户</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input v-model="registerData.username" placeholder="请输入用户名"/>
        </el-form-item>
        <!--真实名 -->
        <el-form-item prop="username">
          <el-input v-model="registerData.realName" placeholder="请输入真名"/>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input v-model="registerData.password" type="password" placeholder="请输入密码"/>
        </el-form-item>
        <!-- 重复密码 -->
        <el-form-item prop="password">
          <el-input v-model="registerData.rePassword" type="password" placeholder="请再次输入密码"/>
        </el-form-item>
        <!-- 手机号 -->
        <el-form-item prop="phone">
          <el-input v-model="registerData.phone" placeholder="请输入手机号"/>
        </el-form-item>

        <!-- 手机验证码 -->
        <el-form-item prop="authCode_m">
          <el-input v-model="registerData.authCode_m" placeholder="请输入手机验证码">
            <template #append>
              <el-button @click="sendSmsCode(registerData.phone)" :disabled="isSmsCodeSending">
                {{ smsCodeBtnText }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <!--邮箱 -->
        <el-form-item  prop="email">
          <el-input v-model="registerData.email" placeholder="请输入邮箱"/>
        </el-form-item>

        <!-- ：邮箱验证码 -->
        <el-form-item prop="authCode_e">
          <el-input v-model="registerData.authCode_e" placeholder="请输入邮箱验证码">
            <template #append>
              <el-button @click="sendEmailCode(registerData.email)" :disabled="isSmsCodeSending2">
                {{ smsCodeBtnText2 }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <!-- 企业管理员专属：企业名 -->
        <el-form-item v-if="registerData.userType === 'enterprise_admin'" prop="email">
          <el-input v-model="registerData.enName" placeholder="请输入企业名称"/>
        </el-form-item>
        <!-- 普通用户专属：企业ID -->
        <el-form-item v-if="registerData.userType === 'normal_user'" prop="enterpriseId">
          <el-input v-model="registerData.enterpriseId" placeholder="请输入企业ID"/>
        </el-form-item>

        <el-form-item class="flex">

        </el-form-item>
        <!-- 注册按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleRegister">注册</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false;clearRegisterData()" >
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>

      <!-- 登录表单 -->
      <el-form ref="loginForm" :model="loginData" v-if="!isRegister" :rules="loginRules">
        <h1 style="font-family: 华文楷体;color:darkslategray">用户登录</h1>
        <!-- 用户名登录 -->
        <el-form-item v-if="loginType === 'username'" prop="username">
          <el-input v-model="loginData.username" placeholder="请输入用户名"/>
        </el-form-item>

        <!-- 手机号登录 -->
        <el-form-item v-if="loginType === 'phone'" prop="phone">
          <el-input v-model="loginData.phone" placeholder="请输入手机号"/>
        </el-form-item>

        <!-- 密码输入 -->
        <el-form-item v-if="loginType === 'username'" prop="password">
          <el-input v-model="loginData.password" type="password" placeholder="请输入密码"/>
        </el-form-item>

        <!-- 验证码输入 -->
        <el-form-item v-if="loginType === 'phone'" prop="authCode">
          <el-input v-model="loginData.authCode" placeholder="请输入验证码">
            <template #append>
              <el-button @click="sendSmsCode(loginData.phone)" :disabled="isSmsCodeSending">
                {{ smsCodeBtnText }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <!-- 登录类型切换 -->
        <el-form-item>
          <el-link @click="toggleLoginType">
            {{ loginType === 'username' ? '使用手机号登录' : '使用用户名登录' }}
          </el-link>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleLogin">登录</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true;clearRegisterData()" >
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>

</template>

<style lang="scss" scoped>
#title {
  font-size: 70px;
  color: darkslategray;
  text-align: center;
  margin-left: 40px;
  text-shadow: #00D1FF 1px 1px 1px;
}
.dark-mode .login-page:deep(.el-row) {
  background: #1a1a1a;
}
.login-page{
  height: 85vh;
  background: linear-gradient(220.55deg, #8FFF85 0%, #39A0FF 100%);
  .bg {
    background: url('@/assets/background.png') no-repeat 60% center / 440px auto;
    border-radius: 20%;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      margin-top: -3vh;
      justify-content: space-between;
    }
  }
}
</style>